import React, { useState, useEffect } from 'react'
import { map } from 'lodash'
import { inject, observer } from 'mobx-react'

import video from '../../store/video'
import Screen from './components/screen'
import ScreenBg from './components/screens-bg'
import './styles/screens.module.scss'

const Screens = ({ mode }) => {
  const { videoSize } = video

  const [screens, setScreens] = useState([])
  const [screenDom, setScreenDom] = useState(null)
  const [sqrt, setSqrt] = useState(1)

  useEffect(() => {
    setSqrt(Math.sqrt(mode))
    sqrt == parseInt(sqrt) ? initScreens() : setScreenDom(null)
  }, [mode])

  useEffect(() => {
    setScreenDom(
      <ScreenBg customStyle={{ flexDirection: 'row', display: 'flex', flexWrap: 'wrap' }}>
        {map(screens, ({ id }, k) => {
          return (
            <Screen id={id} key={k} customStyle={{ width: `calc(100% / ${sqrt})`, height: `calc(100% / ${sqrt})` }} />
          )
        })}
      </ScreenBg>
    )
    video.setScreenArr(screens)
  }, [screens])

  function initScreens() {
    const { w, h } = videoSize
    const screens = []
    for (let i = 0; i < mode; i++) {
      const id = `screen${i}`
      screens.push({ id, status: 'play', player: null })
    }
    setScreens(screens)
  }

  return screenDom
}

export default inject('store')(observer(Screens))
